$(document).ready(function () {
    // 从localStorage加载说说
    function loadThinks() {
        let thinks;
        try {
            thinks = JSON.parse(localStorage.getItem('thinks') || '[]');
            // 为现有说说添加必要属性（如果不存在）
            thinks.forEach(think => {
                if (think.likes === undefined) {
                    think.likes = 0;
                }
                if (think.comments === undefined) {
                    think.comments = [];
                }
                // 初始化评论点赞属性
                think.comments.forEach(comment => {
                    if (comment.likes === undefined) {
                        comment.likes = 0;
                    }
                });
            });
            localStorage.setItem('thinks', JSON.stringify(thinks));
            // 更新说说数量显示
            document.getElementById('thinkCount').textContent = `» ${thinks.length}条说说`;
        } catch (e) {
            console.error('Error parsing thinks:', e);
            thinks = [];
            localStorage.setItem('thinks', JSON.stringify(thinks));
        }
        const container = $('#thinksContainer');
        if (!container.length) {
            console.error('说说容器 #thinksContainer 未找到');
            return;
        }
        container.empty();

        thinks.forEach(think => {
            // 创建说说容器
            const thinkContainer = $('<div>').addClass('think-container');

            // 创建日期元素（外部上方）
            const dateElement = $('<div>').addClass('think-date').text(new Date(think.timestamp).toLocaleString());
            thinkContainer.append(dateElement);

            // 创建说说元素
            const thinkElement = $('<div>').addClass('think-item');
            thinkElement.append($('<div>').addClass('think-content').text(think.content));

            // 评论列表
            const commentsList = $('<div>').addClass('comments-list');
            if (think.comments.length > 0) {
                think.comments.forEach(comment => {
                    const commentElement = $('<div>').addClass('comment-item');
                    commentElement.append($('<div>').addClass('comment-text').html(`<span class="comment-nickname">${comment.nickname}</span>：${comment.content}`));

                    // 评论点赞按钮
                    const commentLikeDiv = $('<div>').addClass('comment-like-container');
                    const commentLikeIcon = comment.likes > 0 ? '❤' : '♡';
                    const commentLikeBtn = $('<button>').addClass('comment-like-btn').html(`<i class="comment-like-icon">${commentLikeIcon}</i>`);
                    const commentLikeCount = $('<span>').addClass('comment-like-count').text(comment.likes);
                    commentLikeDiv.append(commentLikeBtn).append(commentLikeCount);
                    commentElement.append(commentLikeDiv);

                    // 评论点赞事件
                    commentLikeBtn.click(function() {
                        const isLiked = $(this).hasClass('liked');
                        if (isLiked) {
                            comment.likes--;
                            $(this).removeClass('liked');
                            $(this).find('.comment-like-icon').text('♡');
                        } else {
                            comment.likes++;
                            $(this).addClass('liked');
                            $(this).find('.comment-like-icon').text('❤');
                        }
                        commentLikeCount.text(comment.likes);

                        // 更新localStorage
                        let thinks = JSON.parse(localStorage.getItem('thinks') || '[]');
                        const thinkIndex = thinks.findIndex(t => t.timestamp === think.timestamp);
                        if (thinkIndex !== -1) {
                            const commentIndex = thinks[thinkIndex].comments.findIndex(c => c.timestamp === comment.timestamp);
                            if (commentIndex !== -1) {
                                thinks[thinkIndex].comments[commentIndex].likes = comment.likes;
                                localStorage.setItem('thinks', JSON.stringify(thinks));
                            }
                        }
                    });

                    // 初始化评论点赞状态
                    if (comment.likes > 0) {
                        commentLikeBtn.addClass('liked');
                    }
                    commentsList.append(commentElement);
                });
                thinkElement.append(commentsList);
            }

            // 互动按钮区域
            const actionsDiv = $('<div>').addClass('think-actions');

            // 点赞按钮和数量
            const likeDiv = $('<div>').addClass('like-container');
            const likeIcon = think.likes > 0 ? '❤' : '♡';
            const likeBtn = $('<button>').addClass('like-btn').html(`<i class="like-icon">${likeIcon}</i>`);
            const likeCount = $('<span>').addClass('like-count').text(think.likes);
            likeDiv.append(likeBtn).append(likeCount);

            // 回复按钮
            const replyBtn = $('<button>').addClass('reply-btn').text('回复');
            actionsDiv.append(likeDiv).append(replyBtn);
            thinkElement.append(actionsDiv);

            // 回复表单容器
            const replyFormContainer = $('<div>').addClass('reply-form-container').hide();
            const replyForm = $('<form>').addClass('reply-form');

            replyForm.html(`
                <div class="form-group">
                    <label for="replyNickname-${think.timestamp.replace(/[:.]/g, '_')}">昵称:</label>
                    <input type="text" id="replyNickname-${think.timestamp.replace(/[:.]/g, '_')}" class="form-control" placeholder="请输入您的昵称" required>
                    <div class="invalid-feedback">请输入昵称</div>
                </div>
                <div class="form-group">
                    <label for="replyEmail-${think.timestamp.replace(/[:.]/g, '_')}">邮箱:</label>
                    <input type="email" id="replyEmail-${think.timestamp.replace(/[:.]/g, '_')}" class="form-control" placeholder="请输入您的邮箱" required>
                    <div class="invalid-feedback">请输入有效的邮箱地址</div>
                </div>
                <div class="form-group">
                    <label for="replyContent-${think.timestamp.replace(/[:.]/g, '_')}">回复内容:</label>
                    <textarea id="replyContent-${think.timestamp.replace(/[:.]/g, '_')}" class="form-control" rows="3" placeholder="请输入回复内容" required></textarea>
                    <div class="invalid-feedback">请输入回复内容</div>
                </div>
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">提交回复</button>
                    <button type="button" class="btn btn-secondary cancel-reply">取消</button>
                </div>
            `);

            replyFormContainer.append(replyForm);
            thinkElement.append(replyFormContainer);

            // 回复按钮点击事件 - 显示/隐藏回复表单
            replyBtn.click(function () {
                replyFormContainer.toggle();
            });

            // 实时表单验证
            const validateField = function (field) {
                if (!field.checkValidity()) {
                    field.classList.add('is-invalid');
                    field.nextElementSibling.textContent = field.validationMessage;
                } else {
                    field.classList.remove('is-invalid');
                }
            };

            // 为所有输入字段添加验证事件监听
            replyForm.find('input, textarea').on('input blur', function () {
                validateField(this);
            });

            // 取消回复按钮事件
            replyForm.find('.cancel-reply').click(function () {
                replyFormContainer.hide();
            });

            // 回复表单提交处理
            replyForm.submit(function (e) {
                e.preventDefault();

                // 获取表单数据
                const nicknameInput = document.getElementById(`replyNickname-${think.timestamp.replace(/[:.]/g, '_')}`);
                const emailInput = document.getElementById(`replyEmail-${think.timestamp.replace(/[:.]/g, '_')}`);
                const contentInput = document.getElementById(`replyContent-${think.timestamp.replace(/[:.]/g, '_')}`);

                // 验证所有字段
                [nicknameInput, emailInput, contentInput].forEach(validateField);

                // 如果表单验证通过
                if (replyForm[0].checkValidity()) {
                    // 创建新评论
                    const newComment = {
                        nickname: nicknameInput.value,
                        email: emailInput.value,
                        content: contentInput.value,
                        timestamp: new Date().getTime(),
                        likes: 0
                    };

                    // 确保comments数组存在
                    if (!think.comments) think.comments = [];

                    // 添加新评论到当前说说
                    think.comments.push(newComment);

                    // 保存更新后的说说数据
                    let thinks = JSON.parse(localStorage.getItem('thinks') || '[]');
                    const index = thinks.findIndex(t => t.timestamp === think.timestamp);
                    if (index !== -1) {
                        thinks[index] = think;
                        localStorage.setItem('thinks', JSON.stringify(thinks));
                    }

                    // 重新加载说说列表以显示新评论
                    loadThinks();

                    // 隐藏回复表单并重置表单
                    replyFormContainer.hide();
                    replyForm[0].reset();
                }
            });

            // 初始化点赞状态
            if (think.likes > 0) {
                likeBtn.addClass('liked');
            }

            // 点赞事件
            likeBtn.click(function () {
                const isLiked = $(this).hasClass('liked');
                if (isLiked) {
                    think.likes--;
                    $(this).removeClass('liked');
                    $(this).find('.like-icon').text('♡');
                } else {
                    think.likes++;
                    $(this).addClass('liked');
                    $(this).find('.like-icon').text('❤');
                }
                likeCount.text(think.likes);
                // 更新localStorage
                let thinks = JSON.parse(localStorage.getItem('thinks') || '[]');
                const thinkIndex = thinks.findIndex(t => t.timestamp === think.timestamp);
                if (thinkIndex !== -1) {
                    thinks[thinkIndex].likes = think.likes;
                    localStorage.setItem('thinks', JSON.stringify(thinks));
                }
            });

            thinkContainer.append(thinkElement);
            container.append(thinkContainer);
        });
    }

    // 保存说说到localStorage
    function saveThink(think) {
        let thinks;
        try {
            thinks = JSON.parse(localStorage.getItem('thinks') || '[]');
        } catch (e) {
            console.error('Error parsing thinks:', e);
            thinks = [];
        }
        thinks.push(think);
        localStorage.setItem('thinks', JSON.stringify(thinks));
    }

    // 处理表单提交
    $('#thinkForm').submit(function (e) {
        e.preventDefault();

        // 获取表单数据
        const content = $('#thinkContent').val().trim();

        if (!content) {
            $('#thinkContent').addClass('is-invalid');
            return;
        }

        // 创建新说说对象
        const newThink = {
            content: content,
            timestamp: new Date().toISOString(),

            likes: 0
        };

        // 保存说说并重新加载显示
        saveThink(newThink);
        loadThinks();

        // 重置表单
        this.reset();
    });

    // 实时验证 - 说说内容
    $('#thinkContent').on('input', function () {
        const content = $(this).val().trim();
        if (content) {
            $(this).removeClass('is-invalid');
        } else {
            $(this).addClass('is-invalid');
        }
    });

    // 评论表单验证
    $('#nickname, #commentContent').on('input', function () {
        const value = $(this).val().trim();
        if (value) {
            $(this).removeClass('is-invalid');
        } else {
            $(this).addClass('is-invalid');
        }
    });

    $('#email').on('input', function () {
        const email = $(this).val().trim();
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (emailRegex.test(email)) {
            $(this).removeClass('is-invalid');
        } else {
            $(this).addClass('is-invalid');
        }
    });

    // 评论表单提交
    $('#commentForm').submit(function (e) {
        e.preventDefault();

        const nickname = $('#nickname').val().trim();
        const email = $('#email').val().trim();
        const content = $('#commentContent').val().trim();
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        let isValid = true;

        if (!nickname) {
            $('#nickname').addClass('is-invalid');
            isValid = false;
        }
        if (!email || !emailRegex.test(email)) {
            $('#email').addClass('is-invalid');
            isValid = false;
        }
        if (!content) {
            $('#commentContent').addClass('is-invalid');
            isValid = false;
        }

        if (!isValid) return;

        // 获取最新的说说列表并添加评论
        let thinks = JSON.parse(localStorage.getItem('thinks') || '[]');
        if (thinks.length === 0) return;

        // 添加评论到最新的说说
        const latestThinkIndex = thinks.length - 1;
        thinks[latestThinkIndex].comments.push({
            nickname: nickname,
            email: email,
            content: content,
            timestamp: new Date().toISOString()
        });

        localStorage.setItem('thinks', JSON.stringify(thinks));
        loadThinks();

        // 重置评论表单
        this.reset();
    });

    // 初始加载说说
    loadThinks();
});